<template>
	<div class="default-main">
		<cus-form id="blueprint-author-form" collapsable icon="fa fa-search" label="搜索">
			<template #title-after>
				<el-button icon="el-icon-Search" size="small" type="primary" @click.stop="handleSearch">
					搜索
				</el-button>
				<el-button icon="el-icon-Refresh" size="small" type="primary" @click.stop="resetSearch">
					重置
				</el-button>
			</template>
			<template #form>
				<el-form ref="searchForm" :model="params" label-width="auto" @submit.prevent>
					<el-row :gutter="20" justify="space-between">
						<el-col :span="8">
							<el-form-item label="作者名称">
								<el-input v-model="params.authorName_like" clearable placeholder="模糊查询" @keyup.enter="handleSearch"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</template>
		</cus-form>

		<cus-table-title id="blueprint-author-table-title" icon="local-cus-peoples" label="蓝图作者">
			<template #after>
				<el-button v-auth="'g-blueprint-author:saveBlueprintAuthor'" icon="el-icon-Plus" size="small" style="margin-left: 20px" type="primary" @click="toAdd">
					新增
				</el-button>
			</template>
		</cus-table-title>
		<el-table ref="tableRef" v-loading="tableLoading" :data="authorTableData" :header-cell-class-name="handleHeaderCellClass"
		          :max-height="tableMaxHeight" border class="cus-table" fit highlight-current-row max-height="800"
		          @sort-change="elTableSortChange($event, params.orderby, handleSearch)">
			<el-table-column align="center" label="序号" width="60">
				<template v-slot="scope">
					{{ initTableIndex(pageRef, scope.$index) }}
				</template>
			</el-table-column>
			<el-table-column align="center" label="作者名称" min-width="150" prop="authorName" show-overflow-tooltip></el-table-column>
			<el-table-column :label="String($t('table.actions'))" align="center" fixed="right" width="180">
				<template v-slot="{row}">
					<el-button icon="el-icon-Edit" size="small" type="primary" @click="toUpdate(row)">编辑</el-button>
					<el-popconfirm :hide-after="0" :title="`删除该作者（${row.authorName}）？`" confirm-button-type="danger"
					               width="auto" @confirm="deleteBlueprintAuthor(row)">
						<template #reference>
							<el-button v-auth="'g-blueprint-author:deleteBlueprintAuthor'" icon="el-icon-Delete" size="small" type="danger">
								删除
							</el-button>
						</template>
					</el-popconfirm>
				</template>
			</el-table-column>
		</el-table>
		<cus-pagination id="blueprint-author-pagination" ref="pageRef" v-model="authorTableData" v-model:loading="tableLoading" :pageSize="10" :params="params"
		                url="/game/g-blueprint-author/readOnly/pageBlueprintAuthor"/>

		<!-- 对话框（新增、修改） -->
		<el-dialog v-model="dialogVisible" :close-on-click-modal="false" :close-on-press-escape="true" :title="dialogTitle"
		           append-to-body center class="cus-dialog" destroy-on-close draggable width="50%">
			<el-form ref="editFormRef" :disabled="!hasPermission('g-item:saveItem')" :model="blueprintAuthor" :rules="rules" label-width="auto"
			         @submit.prevent>
				<el-form-item label="物品名称" prop="itemName">
					<el-input v-model="blueprintAuthor.authorName" clearable maxlength="100"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button v-auth="'g-blueprint-author:saveBlueprintAuthor'" icon="el-icon-CircleCheck" type="primary" @click="save">
					保存
				</el-button>
				<el-button icon="el-icon-CircleClose" type="warning" @click="dialogVisible = false">
					取消
				</el-button>
			</template>
		</el-dialog>

	</div>
</template>

<script lang="ts" name="BlueprintAuthor" setup>

import {closeLoading, elTableHeaderCellClassName, elTableSortChange, focusFormErrorElement, initTableIndex, messageSuccess, showLoading} from '@/utils/commonUtil'
import CusForm from '@/components/cus-form.vue'
import CusTableTitle from '@/components/cus-table-title.vue'
import CusPagination from '@/components/cus-pagination.vue'
import {onActivated, onMounted, reactive, ref} from 'vue'
import {debounce, type DebouncedFunc} from 'lodash-es'
import {calcMaxHeight} from '@/utils/layoutUtil'
import {useEventListener} from '@vueuse/core'
import {onBeforeRouteLeave} from 'vue-router'
import type {FormInstance, FormRules, TableColumnCtx, TableInstance} from 'element-plus'
import {deleteBlueprintAuthorApi, saveBlueprintAuthorApi} from '@/api/gameData/blueprintAuthor.api'
import {hasPermission} from '@/utils/authUtil'
import {useI18n} from 'vue-i18n'

const pageRef = ref()
const tableRef = ref<TableInstance>()
const editFormRef = ref<FormInstance>()

const {t} = useI18n()

const blueprintAuthor = reactive<GBlueprintAuthor>({
	id: undefined,
	authorName: undefined,
	operator: undefined,
	createTime: undefined,
	updateTime: undefined
})

const rules = reactive<FormRules>({
	authorName: [
		{required: true, message: '请输入作者名称', trigger: 'change'}
	]
})

const authorTableData = ref<GBlueprintAuthor[]>([])
const tableLoading = ref(false)
const tableMaxHeight = ref<number>(800)
const dialogVisible = ref(false)
const dialogTitle = ref('')

const params = reactive({
	authorName_like: undefined,
	orderby: []
})

const handleSearch = () => {
	pageRef.value.reload()
}

const resetParams = () => {
	params.authorName_like = undefined
	params.orderby = []
	// 清除多列的排序状态
	for (const column of tableRef.value?.store.states.columns.value) {
		column.order = null
	}
}

const resetSearch = () => {
	resetParams()
	handleSearch()
}

const resetBlueprintAuthor = () => {
	blueprintAuthor.id = undefined
	blueprintAuthor.authorName = undefined
	blueprintAuthor.operator = undefined
	blueprintAuthor.createTime = undefined
	blueprintAuthor.updateTime = undefined
}

const toAdd = () => {
	resetBlueprintAuthor()
	dialogVisible.value = true
	dialogTitle.value = '新增蓝图作者'
}

const toUpdate = (row: GBlueprintAuthor) => {
	resetBlueprintAuthor()
	Object.assign(blueprintAuthor, JSON.parse(JSON.stringify(row)))
	dialogVisible.value = true
	dialogTitle.value = '编辑蓝图作者信息'
}

const save = () => {
	editFormRef.value!.validate(isValid => {
		if (isValid) {
			saveBlueprintAuthorApi(blueprintAuthor).then(() => {
				if (blueprintAuthor.id) {
					messageSuccess(t('successMessage.update'))
				} else {
					messageSuccess(t('successMessage.add'))
				}
				dialogVisible.value = false
				pageRef.value!.buildData()
			})
		} else {
			focusFormErrorElement()
		}
	})
}

const deleteBlueprintAuthor = (row: GBlueprintAuthor) => {
	showLoading('正在删除')
	deleteBlueprintAuthorApi(row.id!).then(() => {
		messageSuccess('删除成功')
		pageRef.value.buildData()
	}).finally(() => {
		closeLoading()
	})
}

const getTableMaxHeight: DebouncedFunc<() => typeof getTableMaxHeight> = debounce(() => {
	tableMaxHeight.value = calcMaxHeight('#blueprint-author-form', '#blueprint-author-table-title', '#blueprint-author-pagination')
	return getTableMaxHeight
}, 100, {
	leading: true,
	trailing: false,
	maxWait: 100
})

const handleHeaderCellClass = (args: { rows: SysUser[], column: TableColumnCtx<SysUser>, rowIndex: number, columnIndex: number }) => {
	elTableHeaderCellClassName(args, params.orderby)
}

onMounted(() => {
	useEventListener(window, 'resize', getTableMaxHeight()!)
})

// 该页面开启缓存且首次或后续进入时执行，刷新页面不执行
onActivated(() => {
	useEventListener(window, 'resize', getTableMaxHeight()!)
})

onBeforeRouteLeave(() => {
	window.removeEventListener('resize', getTableMaxHeight)
})

</script>

<style lang="scss" scoped>

</style>
